<template>
  <!-- 空海拍下单 -->
  <div class="app-container">
    <el-form
      ref="orderInfo"
      label-width="115px"
      :model="form"
      :rules="rules"
      inline
    >
      <el-row>
        <el-col :span="24">
          <div class="subtitle">收货信息：</div>
        </el-col>
      </el-row>
      <el-form-item label="客户:" prop="customerCode">
        <el-select
          v-model="form.customerCode"
          style="width: 200px;"
          filterable
          placeholder="请选择客户"
          clearable
        >
          <el-option
            v-for="dict in dicts[DictDirection.客户]"
            :key="dict.customerCode"
            :label="dict.customerName"
            :value="dict.customerCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <div class="subtitle">运输信息：</div>
        </el-col>
      </el-row>
      <el-form-item label="客户单号" prop="waybillNo">
        <el-input
          v-model="form.waybillNo"
          style="width: 200px;"
          clearable
          placeholder="请输入单号"
        ></el-input>
      </el-form-item>
      <el-form-item label="国家:" prop="consigneeCountry">
        <el-select
          v-model="form.consigneeCountry"
          filterable
          style="width: 200px;"
          placeholder="请输入内容"
        >
          <el-option
            v-for="dict in dicts[DictDirection.国家]"
            :key="dict.countryCode"
            :label="dict.countryChName"
            :value="dict.countryCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮编" prop="consigneePostcode">
        <el-input
          v-model.trim="form.consigneePostcode"
          style="width: 200px;"
          clearable
          placeholder="请输入邮编"
        ></el-input>
      </el-form-item>
      <el-form-item label="销售产品:" prop="marketProducts">
        <el-select
          v-model="form.marketProducts"
          filterable
          style="width: 200px;"
          placeholder="请输入销售产品"
          clearable
        >
          <el-option label="外配渠道" value="WP"></el-option>
        </el-select>
      </el-form-item>
     
      <el-form-item label="货物类型:" prop="goodsType">
        <el-select
          v-model="form.goodsType"
          filterable
          style="width: 200px;"
          placeholder="请选择货物类型"
        >
          <el-option
            v-for="dict in dicts[DictDirection.货物类型]"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="报价类型:" prop="quotationType">
        <el-select
          v-model="form.quotationType"
          filterable
          style="width: 200px;"
          placeholder="请选择报价类型"
          @change="checkpiece"
        >
          <el-option
            v-for="dict in dicts[DictDirection.报价类型]"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.quotationType != 3" :label="labels" prop="customPrice">
        <el-input
          v-model="form.customPrice"
          clearable
          style="width: 200px;"
          placeholder="请输入价格"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="收货站点:" prop="site">
        <el-select
          v-model="form.site"
          filterable
          style="width: 200px;"
          placeholder="请选择"
        >
          <el-option
            v-for="dict in dicts[DictDirection.收货站点]"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
     
      <el-form-item label="备注:" prop="remarks">
        <el-input
          v-model="form.remarks"
          clearable
          style="width: 200px;"
          type="textarea"
          rows="2"
          placeholder="请输入备注"
        >
        </el-input>
      </el-form-item>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <div class="subtitle">包裹信息：</div>
        </el-col>
        <el-col :span="24">
          <el-scrollbar>
            <div class="mytable">
              <el-table
                border
                :data="form.woodInfoList"
                show-summary
                :summary-method="getSummaries"
              >
                <el-table-column
                  label="序号"
                  align="center"
                  width="55"
                  type="index"
                ></el-table-column>
                <el-table-column label="长(cm)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :rules="[{ validator: validatePass, message: '长不能为空', trigger: 'blur' }]"
                      label-width="0"
                      :prop="`woodInfoList.${$index}.length`"
                    >
                      <el-input-number
                        v-model="row.length"
                        style="width: 100%;"
                        :controls="false"
                        :min="2.54"
                      >
                      </el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="宽(cm)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :rules="[{ validator: validatePass, message: '宽不能为空', trigger: 'blur' }]"
                      label-width="0"
                      :prop="`woodInfoList.${$index}.width`"
                    >
                      <el-input-number
                        v-model="row.width"
                        :controls="false"
                        style="width: 100%;"
                        :min="2.54"
                      >
                      </el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="高(cm)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :rules="[{ validator: validatePass, message: '高不能为空', trigger: 'blur' }]"
                      label-width="0"
                      :prop="`woodInfoList.${$index}.height`"
                    >
                      <el-input-number
                        v-model="row.height"
                        :controls="false"
                        style="width: 100%;"
                        :min="2.54"
                      >
                      </el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="重(kg)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :rules="[{ validator: validatePass, message: '重量不能为空', trigger: 'blur' }]"
                      label-width="0"
                      :prop="`woodInfoList.${$index}.weight`"
                    >
                      <el-input-number
                        v-model="row.weight"
                        :controls="false"
                        style="width: 100%;"
                        :min="0"
                      >
                      </el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="件数" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item
                      label-width="0"
                      :rules="[{ validator: validatePass, message: '件数不能为空', trigger: 'blur' }]"
                      :prop="`woodInfoList.${$index}.pieceNumber`"
                    >
                      <el-input-number
                        v-model="row.pieceNumber"
                        :controls="false"
                        style="width: 100%;"
                        :min="0"
                      >
                      </el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="{ row, $index }">
                    <el-button
                      size="small"
                      icon="el-icon-delete"
                      text
                      @click="handleDeletePackage(row, $index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-scrollbar>
        </el-col>
        <el-col :span="24">
          <el-button
            :icon="Plus"
            text
            type="primary"
            @click="handleAddPackage"
          >
            添加包裹
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <div class="top-right-btn">
        <el-button type="primary" :loading="listloading" @click="submit">下单</el-button>
      </div>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { orderInsert } from '@/api/expressManager/external'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import userStore from '@/store/modules/user'

const user = userStore()
const userIds = user.user.userId
const deptIds = user.user.deptId
let
  // eslint-disable-next-line prefer-const
  labels = ref(null)
const orderInfo = ref(),
  {
    appContext: {
      config: {
        globalProperties: { $validateForm },
      },
    },
  } = getCurrentInstance()
const dicts = useDicts()
dicts.setDicts(DictDirection.客户)
dicts.setDicts(DictDirection.快递产品)
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.货物类型)
dicts.setDicts(DictDirection.报价类型)
dicts.setDicts(DictDirection.收货站点)
const rules = {
  consigneeCountry: [{ required: true, message: '国家不能为空', trigger: ['change', 'blur'] }],
  marketProducts: [{ required: true, message: '销售产品不能为空', trigger: 'change' }],
  upsOrFede: [{ required: true, message: '渠道不能为空', trigger: 'change' }],
  goodsType: [{ required: true, message: '货物类型不能为空', trigger: 'change' }],
  customerName: [{ required: true, message: '请输入客户编码', trigger: 'change' }],
  customPrice: [{ required: true, message: '请输入自定价格', trigger: 'blur' }],
  customerCode: [{ required: true, message: '请选择客户名称', trigger: ['blur', 'change'] }],
  receivingSite: [{ required: true, message: '请选择收货站点', trigger: ['blur', 'change'] }],
}
const listloading = ref(false)
const { proxy } = getCurrentInstance() as any
const form = ref({
  customerCode: '',
  waybillNo: '',
  customPrice: '',
  consigneeCountry: 'US',
  consigneePostcode: '',
  marketProducts: '',
  upsOrFedex: '',
  goodsType: 1,
  dataSources: '1',
  uesrId: userIds,
  deptId: deptIds,
  transportType: 9,
  quotationType: 3,
  site: '',
  remarks: '',
  woodInfoList: [{ length: '', width: '', height: '', weight: '', pieceNumber: '' }],
})
// eslint-disable-next-line no-redeclare
interface form {
  woodInfoList: string;
  length: string;
  widht: string;
  height: string;
  weight: string;
  pieceNumber: string
}

const checkpiece = () => {
  const ss = form.value.quotationType
  console.log(ss)
  
  if (ss == '1') {
    labels.value = '单价'
    console.log(1)
  }
  if (ss == '2') {
    console.log(2)
    labels.value = '总价'
  }
  if (ss == '4') {
    labels.value = '立方总价'
    console.log(labels.value)
  }
  if (ss == '3') {
    form.value.customPrice = ''
  }
}

// 添加包裹

const handleAddPackage = () => {
  form.value.woodInfoList.push({ length: '', width: '', height: '', weight: '', pieceNumber: '' })
}
const validatePass = (rule, value, callback) => {
  if (value === '' || value == 0 || value == undefined) {
    callback(new Error('请输入包裹信息'))
  } else {
    callback()
  }
}
// 删除包裹
const handleDeletePackage = (row: { [key: string]: any }, index) => {
  ElMessageBox.confirm('此操作将永久删除该包裹信息, 是否继续?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => {
    form.value.woodInfoList.splice(index, 1)
    ElMessage.success('删除成功')
  })
  .catch(() => {
    ElMessage.error('删除失败')
  })
}
// 提交

const submit = () => {
  $validateForm(orderInfo.value, () => {
    listloading.value = true
    orderInsert(form.value).then(res => {
      if (res.code == 200) {
        ElMessage.success('下单成功')
        proxy.$refs.orderInfo.resetFields()
        listloading.value = false
      } else {
        ElMessage.error(res.msg)
        listloading.value = false
      }
    }).catch(err => {
      console.log(err)
      
      listloading.value = false
    })
    // listloading.value = false
  })
}
// 合计
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    // const data = Array.from(data)
    const values = data.map((item) => Number(item.pieceNumber))
    sums[5] = values.reduce((prev: string, curr: string) => {
      const value = Number(curr)
      // eslint-disable-next-line no-restricted-globals
      if (!isNaN(value)) {
        return prev + curr
      }
      return prev
    }, 0)
  })
  return sums
}
</script>
<style lang="less" scoped>
.subtitle {
  font-size: 18px;
  font-weight: 700;
}
.app-container {
  background: #fff;
  margin: 10px;
  border-radius: 10px;
  padding: 10px;
}
</style>
